// 三方协议查询页面逻辑
const SafetyCareAPI = require('../../../js/services/api/safetyCareService');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    agreementInfo: null,
    isLoading: true,
    agreementStatusText: '已生效'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.loadAgreementInfo();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.agreementInfo) {
      this.loadAgreementInfo();
    }
  },

  /**
   * 加载协议信息
   */
  loadAgreementInfo: function() {
    this.setData({ isLoading: true });
    // 获取当前用户ID（实际项目中应从登录状态获取）
    const userId = wx.getStorageSync('userId') || 'default_user_id';

    SafetyCareAPI.getAgreementInfo(userId)
      .then(res => {
        if (res && res.agreementInfo) {
          this.setData({
            agreementInfo: res.agreementInfo,
            agreementStatusText: this.getAgreementStatusText(res.agreementInfo.status)
          });
        } else {
          this.setData({ agreementInfo: null });
        }
      })
      .catch(err => {
        console.error('获取协议信息失败:', err);
        wx.showToast({ title: '加载协议失败', icon: 'none' });
      })
      .finally(() => {
        this.setData({ isLoading: false });
      });
  },

  /**
   * 获取协议状态文本
   */
  getAgreementStatusText: function(status) {
    const statusMap = {
      'active': '已生效',
      'pending': '待生效',
      'expired': '已过期',
      'revoked': '已撤销'
    };
    return statusMap[status] || '未知状态';
  },

  /**
   * 格式化日期显示
   */
  formatDate: function(dateStr) {
    if (!dateStr) return '——';
    const date = new Date(dateStr);
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
  },

  /**
   * 查看完整协议
   */
  viewFullAgreement: function() {
    wx.navigateTo({
      url: '/pages/safety-care/agreement/full-agreement?agreementId=' + this.data.agreementInfo.agreementId
    });
  },

  /**
   * 前往签约页面
   */
  navigateToSign: function() {
    wx.navigateTo({
      url: '/pages/safety-care/agreement/sign-agreement'
    });
  }
});